package com.bitcola.security.admin.biz;

import com.bitcola.security.admin.entity.ApplyProject;
import com.bitcola.security.admin.mapper.ColaLabsProjectMapper;
import com.bitcola.security.common.msg.AppResponse;
import com.bitcola.security.common.msg.TableResultResponse;
import com.bitcola.security.common.util.AdminQuery;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.List;

/**
 * @date 2019/11/14 13:57
 */
@Service
public class ColaLabsProjectBiz {

    @Autowired
    ColaLabsProjectMapper colaLabsProjectMapper;

    public TableResultResponse<ApplyProject> projectList(AdminQuery query) {
//        暂无查询条件
//        String name = query.get("name").toString();
//        String coinStatus = query.get("coinStatus").toString();
//      pageHelper分页
        PageHelper.startPage(query.getPage(), query.getLimit());
        List<ApplyProject> list = colaLabsProjectMapper.projectList("");
        PageInfo<ApplyProject> pageInfo = new PageInfo<>(list);
        return new TableResultResponse<>(pageInfo.getTotal(), pageInfo.getList());
    }


    public AppResponse addProject(ApplyProject applyProject) {
        Assert.notNull(applyProject.getId(), "id不能为空");
        boolean validData = validData(applyProject);
        if (!validData) {
            return new AppResponse<>(500, "数据异常");
        }
        applyProject.setTimestamp(System.currentTimeMillis());
        colaLabsProjectMapper.insertSelective(applyProject);
        return AppResponse.ok();
    }

    public AppResponse updateProject(String id, ApplyProject applyProject) {
        ApplyProject project = colaLabsProjectMapper.selectByPrimaryKey(id);
        Assert.notNull(project, "数据错误");
        boolean validData = validData(applyProject);
        if (!validData) {
            return new AppResponse<>(500, "数据异常");
        }
        BeanUtils.copyProperties(applyProject, project);
        colaLabsProjectMapper.updateByPrimaryKeySelective(project);
        return AppResponse.ok();
    }

    boolean validData(ApplyProject applyProject) {
        BigDecimal maxValue = BigDecimal.valueOf(1);
        BigDecimal minValue = BigDecimal.valueOf(0);
        if (applyProject.getMaxDudect() != null &&
                (applyProject.getMaxDudect().compareTo(maxValue) > 0 || applyProject.getMaxDudect().compareTo(minValue) < -1)) {
            return false;
        }
        if (applyProject.getDudect() != null &&
                (applyProject.getDudect().compareTo(maxValue) > 0 || applyProject.getDudect().compareTo(minValue) < -1)) {
            return false;
        }
        return true;
    }
}
